layui.define(['form', 'laytpl','staticData'], function (exports) {
    var $ = layui.$, com = layui.com, request = layui.request, form = layui.form, laytpl = layui.laytpl,search = layui.router().search, staticData = layui.staticData,fn = {
        params: {
            page: 1
            , limit: 10
        },
        list:[]
        ,renderWaitOrder: function(){
            let $waitEditOrder = $('div[status-id]'),docIds=[];
            $waitEditOrder.each(function (i,o) {
                docIds.push($(o).attr('status-id'));
            });
            if(docIds.length>0){
                request.postForm('/scm/statusHistory/recentInfos',{domainIds:docIds.join(','),domainType:'com.tsfyun.scm.entity.order.ImpOrder',nowStatusId:'waitEdit'}).then(res=>{
                    $.each(res.data || [],function (i,o) {
                        laytpl($('#tpl-wait-edit').html()).render(o, function (html){
                            $('div[status-id="' + o.domainId +'"]').html(html);
                        });
                    });
                });
            }
        }
        ,query: function () {
            com.showLoading();
            fn.list = [];
            let params = $.extend({},fn.params,$('#form-order-list').serializeJson());
            request.post('/scm/client/impOrder/list',params).then(res => {
                fn.list = res.data;
                // 模板渲染
                laytpl($('#tpl-order-list').html()).render(res.data, function (html) {
                    $('#tab-order-list').find('tbody').remove();
                    $('#tab-order-list').append(html);
                    // 重新渲染表单内表单数据
                    com.chooseCheckbox($('#checkbox-order-list-check-all'),false);
                    form.render(null, 'form-order-list');
                    fn.renderWaitOrder();
                    // 滚动条置顶
                    layui.view().container.scrollTop(0);
                    // 初始化复制功能
                    com.createCopyContent();
                    // 付汇按钮
                    fn.mergePay();
                });
                // 开启分页
                com.pagination('order-list-pagination', res.count, fn.params, function () {
                    fn.query();
                });
                if(res.count>0){
                    $('#order-list-pagination').show();
                    $('.blank-list').hide();
                }else{
                    $('#order-list-pagination').hide();
                    $('.blank-list').show();
                }
            });
        },
        removeOrder(orderId,orderNo){
            layer.confirm('您确定要删除该订单【' + orderNo + '】吗?',{icon: 3,closeBtn:false,title:'温馨提示'},function(index){
                request.postForm('/scm/client/impOrder/delete',{id:orderId}).then(res => { 
                    layer.msg('删除成功',{
                        time: 2000
                    }); 
                    //重新加载
                    fn.clearQuery();
                });
                layer.close(index);
            });
        }
        ,clearQuery(){
            fn.params.page = 1;
            fn.params.limit = 10;
            fn.query();
        }
        ,setDate(othis){
            form.val('form-order-list',{'orderDateStart':othis.attr('orderDateStart'),'orderDateEnd':othis.attr('orderDateEnd')});
            fn.clearQuery();
        }
        ,setReceivingMode(othis){
            form.val('form-order-list',{'receivingMode':othis.attr('item-value')});
            fn.clearQuery();
        }
        ,judstatus(st){
            if(['waitEdit','waitPrice','waitExamine'].contain(st)){
                return 2;
            }else if(['waitInspection','waitConfirmImp','waitFKExamine'].contain(st)){
                return 3;
            }else if(['waitDeclare','waitClearance'].contain(st)){
                return 4;
            }else if(['cleared'].contain(st)){
                return 5;
            }
            return 1;
        }
        ,mergePay(){
            $('#btn-order-list-merge-pay').attr({'disabled':$('input[type="checkbox"][name="orderId"]:checked').length==0});
        }
        ,mergePayApply(){
            let $orderId = $('input[type="checkbox"][name="orderId"]:checked'),orderIds=[];
            $orderId.each((i,o)=>{
                orderIds.push($(o).val());
            });
            let currencyName = null,isAgain=true;
            fn.list.some(item=>{
                if(orderIds.contain(item.id)){
                    if(currencyName!=null&&currencyName!=item.currencyName){
                        layer.msg('订单【'+item.docNo+'】所选币制不一致，无法合并付汇');
                        isAgain = false;
                        return true;
                    }
                    if(item.totalPrice==0||item.totalPrice <= item.payVal){
                        layer.msg('订单【'+item.docNo+'】可申请付汇金额不足');
                        isAgain = false;
                        return true;
                    }
                    currencyName = item.currencyName;
                }
            });
            if(isAgain){
                location.hash = '/finance/payApply/id='+orderIds.join(',');
            }
        }
        ,async init(){
            let now = new Date(),dates=[];
            now.setMonth(now.getMonth() - 1);
            dates.push({'title':'近一个月订单',orderDateStart:com.formatDate(now,'yyyy-MM-dd'),orderDateEnd:''});
            now.setMonth(now.getMonth() - 2);
            form.val('form-order-list',{'orderDateStart':com.formatDate(now,'yyyy-MM-dd')});
            dates.push({'title':'近三个月订单',orderDateStart:com.formatDate(now,'yyyy-MM-dd'),orderDateEnd:''});
            let year = new Date().getFullYear();
            dates.push({'title':'今年内订单',orderDateStart:year+'-01-01',orderDateEnd:''});
            for(var i=1;i<5;i++){
                let yearLast = new Date();
                yearLast.setFullYear(year-i);
                yearLast.setMonth(0);
                yearLast.setDate(1);
                let item = {'title':yearLast.getFullYear()+'年订单',orderDateStart:com.formatDate(yearLast,'yyyy-MM-dd'),orderDateEnd:''};
                yearLast.setFullYear(yearLast.getFullYear()+1);
                yearLast.setDate(yearLast.getDate() - 1);
                item.orderDateEnd = com.formatDate(yearLast,'yyyy-MM-dd');
                dates.push(item);
            }
            let $orderListDate = $('#order-list-date'),dataItems=[];
            dates.forEach(o =>{
                dataItems.push('<li><a href="javascript:" orderDateStart="'+o.orderDateStart+'" orderDateEnd="'+o.orderDateEnd+'"><b></b>'+o.title+'</a></li>');
            });
            $orderListDate.find('.more-operation-txt div').html(dates[1].title).addClass('color-theme');
            $orderListDate.find('.more-operation-list ul').html(dataItems.join(''));
            $($orderListDate.find('.more-operation-list ul li a')[1]).addClass('curr');

            let rmdata = await staticData.getReceivingMode(),$orderListRm = $('#order-list-rm'),rmDataItems=[];
            rmDataItems.push('<li><a href="javascript:" item-value=""><b></b>送货方式</a></li>');
            rmdata.forEach(o =>{
                rmDataItems.push('<li><a href="javascript:" item-value="'+o.value+'"><b></b>'+o.label+'</a></li>');
            });
            $orderListRm.find('.more-operation-txt div').html('送货方式');
            $orderListRm.find('.more-operation-list ul').html(rmDataItems.join(''));
            $($orderListRm.find('.more-operation-list ul li a')[0]).addClass('curr');
        }
    };
    fn.init();
    form.render(null, 'form-order-list');
    // 订单状态
    if(com.isNotEmpty(search.statusId)) {
        $('#queryStatus').find('a[status]').removeClass('curr');
        $('#queryStatus').find('a[status=' + search.statusId +']').addClass('curr');
        form.val('form-order-list',{'orderStatusId':search.statusId});
    }
    fn.clearQuery();
    form.on('submit(search-order-list)',function () {
        fn.clearQuery();
    });
    form.on('checkbox(checkbox-order-list-status)',function () {
        fn.clearQuery();
    });
    // 状态查询
    $('#queryStatus').find('a[status]').click(function () {
        $('#queryStatus').find('a[status]').removeClass('curr');
        $(this).addClass('curr');
        form.val('form-order-list',{'orderStatusId':$(this).attr('status')});
        fn.clearQuery();
    });

    form.on('checkbox(checkbox-order-list-check-all)',function (data) {
        com.chooseCheckbox($('input[type="checkbox"][name="orderId"]'),data.elem.checked);
        form.render('checkbox', 'form-order-list');
        fn.mergePay();
    });
    form.on('checkbox(checkbox-order-list-order-id)',function (data) {
        com.chooseCheckbox($('#checkbox-order-list-check-all'),($('input[type="checkbox"][name="orderId"]').length == $('input[type="checkbox"][name="orderId"]:checked').length));
        form.render('checkbox', 'form-order-list');
        fn.mergePay();
    });

    exports('orderList', fn);
});